<template>
  <el-dialog
    v-model="visible"
    title="批量导入"
    width="1000px"
    :close-on-click-modal="false"
    :before-close="hide"
  >
    <!-- 业务员信息 -->
    <div v-if="!isEmpty(salesmansData)">
      {{ salesmansData.nickName }} ({{ salesmansData.phonenumber }})
    </div>
    <!-- 进度进度条 -->
    <div>
      <el-progress :percentage="percentage" :stroke-color="progressColor" />
      <div class="mt-3 text-gray-500">
        <template v-if="percentage < 100"> {{ current }}/{{ total }} 正在导入... </template>
        <template v-else> 导入完成，请检查错误信息 </template>
      </div>
    </div>

    <!-- 错误记录展示 -->
    <div v-if="errorList.length > 0" class="mt-5">
      <!-- 导出按钮 -->
      <div class="handleErrs">
        <h4>异常记录（{{ errorList.length }} 条）</h4>
        <div>
          <el-button @click="togglePause" :disabled="finished">
            {{ isPaused ? '继续' : '暂停' }}
          </el-button>
          <el-button type="primary" @click="exportErrorList">导出异常记录</el-button>
        </div>
      </div>

      <el-table :data="pagedErrorList" border>
        <el-table-column prop="index" label="序号" width="70" />
        <el-table-column prop="info" label="信息" min-width="220" />
        <el-table-column prop="error" label="错误原因" min-width="180" />
      </el-table>

      <div class="pagination">
        <el-pagination
          background
          layout="prev, pager, next"
          :current-page="errorPage"
          :total="errorList.length"
          :page-size="errorSize"
          @update:current-page="errorPage = $event"
        />
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import {
  addCustomer,
  listCustomer,
  updateCustomer,
  updateCustomerSalesman
} from '../../../../api/customers';
import { addFollowRecord } from '../../../../api/follow';
import { flattenDeep, isEmpty } from 'lodash';

const props = defineProps<{
  data: any[];
  salesmansId: string;
  salesmansData: any;
}>();

// 弹窗显示
const visible = ref(false);

// 当前进度
const current = ref(0);
const total = computed(() => props.data.length);

// 进度百分比
const percentage = computed(() =>
  total.value === 0 ? 0 : Math.round((current.value / total.value) * 100)
);

// 是否全部完成
const finished = computed(() => current.value >= total.value);

// 暂停控制
const isPaused = ref(false);

// 动态改变进度条颜色
const progressColor = computed(() => {
  return percentage.value >= 100 ? '#67C23A' : '#409EFF';
});

/**
 * 错误记录
 */
const errorList = ref<any[]>([]);
const errorPage = ref(1);
const errorSize = 5;

const pagedErrorList = computed(() => {
  const start = (errorPage.value - 1) * errorSize;
  return errorList.value.slice(start, start + errorSize);
});

/**
 * 等待继续（暂停逻辑）
 */
const waitUntilResume = () =>
  new Promise<void>((resolve) => {
    const timer = setInterval(() => {
      if (!isPaused.value) {
        clearInterval(timer);
        resolve();
      }
    }, 150);
  });

/**
 * 核心：处理单条客户导入逻辑
 */
const handleRow = async (row: any) => {
  try {
    const {
      name,
      phone,
      address,
      orderCategory,
      isAddWechat,
      remark1 = '',
      remark2 = '',
      remark3 = ''
    } = row;

    // 添加客户
    await addCustomer({
      customerName: name,
      customerPhone: phone,
      customerSource: '复购导入',
      contactAddress: address,
      createBy: '',
      remark: ''
    });

    // 查询添加的客户id
    const res = await listCustomer({
      pageSize: 1,
      pageNum: 1,
      customerPhone: phone
    });

    if (res.code !== 200) {
      throw new Error(`客户查询接口错误：${res.msg || res.message || '未知错误'}`);
    }

    if (!res.rows.length) {
      throw new Error(`未查到客户信息（手机号：${phone}）`);
    }

    const customer = res.rows[0];
    const salesman = customer.salesman;

    if (salesman?.salesmanId) {
      throw new Error(
        `该客户已绑定业务员：${salesman.salesmanName || salesman.nickName || '未知业务员'}-${salesman.salesmanPhone}`
      );
    }

    // 更新客户归属
    await updateCustomer({
      customerId: customer.customerId,
      isAddWechat,
      category: orderCategory
    });

    const remarks = [remark1, remark2, remark3];
    const flatDeepRemark = flattenDeep(
      remarks.filter(Boolean).map((v) =>
        v
          .split(/\s{2,}/)
          .map((s: string) => s.trim())
          .filter(Boolean)
      )
    );

    for (const remark of flatDeepRemark) {
      if (!remark) continue;

      const followRes = await addFollowRecord({
        customerId: customer.customerId,
        typeCode: 2,
        followRemark: remark,
        contactNextTime: '',
        usageAmount: 0
      });

      if (followRes.code !== 200) {
        throw new Error(`添加备注失败：${followRes.msg || '未知错误'}`);
      }
    }

    await updateCustomerSalesman({
      customerId: customer.customerId,
      salesmanId: props.salesmansId
    });
  } catch (err: any) {
    throw new Error(err?.message || String(err));
  }
};

/**
 * 主流程：执行导入
 */
const startImport = async () => {
  current.value = 0;
  errorList.value = [];
  isPaused.value = false;

  for (const [index, row] of props.data.entries()) {
    if (isPaused.value) await waitUntilResume();

    try {
      await handleRow(row);
    } catch (err: any) {
      errorList.value.unshift({
        index: index + 1,
        info: JSON.stringify(row),
        error: err?.message || String(err)
      });
    }

    current.value++;
  }
};

/**
 * 导出错误记录（手动或自动）
 */
const exportErrorList = () => {
  if (!errorList.value.length) return;
  const header = '序号,信息,错误原因\n';
  const csv = errorList.value
    .map((item) => `${item.index},"${item.info.replace(/"/g, '""')}","${item.error}"`)
    .join('\n');

  const blob = new Blob([header + csv], { type: 'text/csv;charset=utf-8;' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  console.log('props ==> ', props);
  a.download = `${props.salesmansData.nickName}-${new Date().getTime()}异常记录导出.csv`;
  a.click();
  URL.revokeObjectURL(url);
};

/**
 * 弹窗关闭逻辑
 */
const hide = (done: () => void) => {
  // 仅当导入已完成时，才自动导出错误记录
  if (finished.value && errorList.value.length > 0) {
    exportErrorList();
  }

  // 无论是否完成，都允许关闭
  done();
  visible.value = false; // 可选，因 v-model 会同步，但保留无害
};

/**
 * UI 操作
 */
const show = () => {
  visible.value = true;
  startImport();
};

// 暂停 / 继续
const togglePause = () => {
  isPaused.value = !isPaused.value;
};

defineExpose({ show, hide });
</script>

<style lang="scss">
.handleErrs {
  display: flex;
  justify-content: space-between;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>
